import a from 'axios'
import ls from 'store2'
import qs from 'qs'
// import {openLoading, hideLoading} from '~/components/loading/index'
const axios = a.create({
  baseURL: '/client-api',
  timeout: 30000000,
})

const getHeader = () => {
  let headers = {
    'content-type': 'application/json',
    'Api-Version': '2.2.1',
  }
  return headers
}
// 返回状态判断
axios.interceptors.request.use(
  function(config) {
    // 每次请求时会从localStorage中获取token
    let token = ls.get('tokensyxk')
    // let token=null
    if (token) {
      config.headers.common['accessToken'] = token
    }
    // openLoading()
    return config
  },
  function(error) {
    return Promise.reject(error)
  }
)
axios.interceptors.response.use(
  (res) => {
    if (res.data.code === '0') {
      return res.data
    } else if (res.data.code === '11') {
      ls.remove('tokensyxk')
      // let types;
      // if(window.$nuxt.$route.name==='univ'){types='yxk'}else if(window.$nuxt.$route.name==='user'){types='users'}
      return window.$nuxt.$router.replace('../login/msgLogin')
    }
    setTimeout(() => {
      // hideLoading()
    }, 1000)

    return res
  },
  (error) => {
    return Promise.reject(error)
  }
)

let loginLoading = false
let loginPromise
let methods = {
  posts(url) {
    return axios({
      method: 'POST',
      url,
      headers: getHeader(),
    })
  },
  put_http(url, params) {
    return axios({
      method: 'PUT',
      url,
      data: params,
      headers: getHeader(),
    })
  },
  delete_http(url, params) {
    return axios({
      method: 'DELETE',
      url,
      data: params,
      headers: getHeader(),
    })
  },
  post_http(url, params) {
    return axios({
      method: 'POST',
      url,
      data: params,
      headers: getHeader(),
    })
  },
  postForm_http(url, params) {
    let headers = getHeader()
    headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8'
    return axios({
      method: 'POST',
      url,
      data: qs.stringify(params),
      headers,
    })
  },
  get_http(url, params) {
    return axios({
      method: 'GET',
      url,
      params,
      headers: getHeader(),
    })
  },
  put(url, params, requireLogin) {
    if (requireLogin && loginLoading) {
      return loginPromise.then(() => {
        return this.put_http(url, params)
      })
    } else {
      return this.put_http(url, params)
    }
  },
  get(url, params, requireLogin) {
    if (requireLogin && loginLoading) {
      return loginPromise.then(() => {
        return this.get_http(url, params)
      })
    } else {
      return this.get_http(url, params)
    }
  },
  post(url, params, requireLogin) {
    if (requireLogin && loginLoading) {
      return loginPromise.then(() => {
        return this.post_http(url, params)
      })
    } else {
      return this.post_http(url, params)
    }
  },
}
export default methods
